package com.atguigu.fink.chapter02;

import com.atguigu.fink.bean.WaterSensor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.table.functions.ScalarFunction;

/**
 * @Author lzc
 * @Date 2022/11/28 09:06
 */
public class Flink01_Scalar {
    public static void main(String[] args) throws Exception {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 2000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
        DataStreamSource<WaterSensor> stream = env.fromElements(
            new WaterSensor("safa1", 1L, 10),
            new WaterSensor("s1", 2L, 10),
            new WaterSensor("s2", 3L, 20),
            new WaterSensor("s1", 4L, 30),
            new WaterSensor("s1", 5L, 40),
            new WaterSensor(null, 5L, 40),
            new WaterSensor("s1", 6L, 50)
        );
        
        StreamTableEnvironment tEnv = StreamTableEnvironment.create(env);
        Table table = tEnv.fromDataStream(stream);
        tEnv.createTemporaryView("sensor", table);
        
        // 1. table api 中使用
        // 1.1 内联用法
        /*table
            .select($("id"), call(MyUpper.class, $("id")).as("upper_id"))
            .execute()
            .print();*/
        // 1.2. 先注册再使用
        tEnv.createTemporaryFunction("my_upper", MyUpper.class);
        /*table
            .select($("id"), call("my_upper", $("id")).as("upper_id"))
            .execute()
            .print();*/
        
        // 2. 在sql 中使用
        // 先注册自定义函数
        tEnv.sqlQuery("select " +
                          " id, " +
                          " my_upper(id) " +
                          "from sensor")
            .execute()
            .print();
        
    
    
    }
    
    public static class MyUpper extends ScalarFunction {
        // 定义一个约定好的方法
        // 返回值: 必须有, 类型根据情况来定
        // 方法名: 必须是 eval
        // 参数列表: 根据实际情况定
        public String eval(String s){
            if (s != null) {
                return s.toUpperCase();
            }
            return null;
        }
    }
}
